package net.tycmc.cty.ctyms.timejob.iems.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.configuration.ConfigurationException;
import com.tycmc.functions.util.StringUtil;
import net.tycmc.cty.ctyms.timejob.common.DynamicReadConfig;
import net.tycmc.bulb.common.util.DateUtil;
import net.tycmc.bulb.common.util.MapGetter;
import net.tycmc.cty.ctyms.timejob.common.DateRegUtil;
import net.tycmc.cty.ctyms.timejob.common.ListUtil;
import net.tycmc.cty.ctyms.timejob.iems.dao.MaintAlertsDAO;
import net.tycmc.cty.ctyms.timejob.iems.dao.SMSInfoDAO;

public class MaintAlertsService {
	
	private MaintAlertsDAO maintAlertsDAO;
	private SMSInfoDAO smsInfoDAO; 
	public void setSmsInfoDAO(SMSInfoDAO smsInfoDAO) {
		this.smsInfoDAO = smsInfoDAO;
	}
	public void setMaintAlertsDAO(MaintAlertsDAO maintAlertsDAO) {
		this.maintAlertsDAO = maintAlertsDAO;
	}
	/**
	 * 保养提示
	 **/
	public void startWork() {
		Date date1 = new Date();
		System.out.println("开始执行保养提示："+date1.toString());
		Map<String,Object> map = this.maintAlertsDAO.querySysParmConfig();
		
		//二期优化：是否需要备份数据
		String isbakTable="";
		try {
			isbakTable = DynamicReadConfig.getConfigProperty("config.properties", "MaintAlerts");
		} catch (ConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(!StringUtil.isValid(isbakTable)){
			isbakTable = "0";
		}
		
		
		//保内工作小时数
		float mtnInHours = map.get("SysPC_MtnInHours")!=null?Float.parseFloat(map.get("SysPC_MtnInHours").toString()):0;
		//保内公里数
		float mtnInKm = map.get("SysPC_MtnInKm")!=null?Float.parseFloat(map.get("SysPC_MtnInKm").toString()):0;
		//固定时间间隔的设备及其上次提示时间 <设备ID,上次提示时间>,可为空HashMap，但不可为null
		Map<String,String> gapAleVclDay = this.getPreMtnGapAlarmInfo();
		//当前是否发送保养短信
		boolean mtnAlertSMS = false;
		if(this.smsInfoDAO.getSmsSendList().contains("SMSAS_SMSMtnNew")){
			mtnAlertSMS = true;
		}
		/*录入保养计划提醒信息列表、发送短信、提示表*start*/
		//此次保养提示处理的设备信息集合<保养方式,设备信息集合>
		Map<String,List<Map<String,Object>>> workMap = this.getWorkVclInfos();
		if(null!=workMap&&!workMap.isEmpty()){
			Set<String> key = workMap.keySet();
			for(Iterator<String> it = key.iterator();it.hasNext();){
				String mtnType = it.next();
				int type = Integer.parseInt(mtnType);
				switch(type){
				    case 1://工作小时数据
				    	this.maintAlertsOfWorkTime(mtnInHours,workMap.get(mtnType),mtnAlertSMS,type,isbakTable);
				    	break;
				    case 2://公里数
				    	this.maintAlertsOfRunKm(mtnInKm,workMap.get(mtnType),mtnAlertSMS,type,isbakTable);
				    	break;
				    case 3://固定时间间隔
				    	this.maintAlertsOfGapDays(gapAleVclDay,workMap.get(mtnType),mtnAlertSMS,type,isbakTable);
				    	break;
				    default:break;
				}
			}
		}
		/*录入保养计划提醒信息列表、发送短信、提示表*end*/
		
		/*根据保养计划提醒信息列表   录入保养计划提醒信息表**start*/
		this.maintAlertsDAO.InsertMaintAlarm(isbakTable);
		/*根据保养计划提醒信息列表   录入保养计划提醒信息表**end*/
		
		/*更新此次处理的保养提示的状态（保养计划提醒信息列表、提示表）*逻辑暂未有*/
		System.out.println("保养提示执行结束："+new Date().toString()+",用时："+(new Date().getTime()-date1.getTime())/(1000)+"秒");
	}
	/**
	 * 固定时间间隔
	 **/
	private void maintAlertsOfGapDays(Map<String, String> gapAleVclDay,
			List<Map<String, Object>> vclLists,boolean mtnAlertSMS,int mtnType,String isbakTable) {
		if(null!= vclLists && !vclLists.isEmpty()){
			String preDate = null;
			for(Map<String,Object> oneVcl:vclLists){
				String vclID = MapGetter.getString(oneVcl,"VehicleID");
				if(StringUtil.isValid(MapGetter.getString(oneVcl, "MaintfixeStartDate"))){
					if(StringUtil.isValid(gapAleVclDay.get(vclID))){
						if(DateRegUtil.compare(gapAleVclDay.get(vclID), MapGetter.getString(oneVcl, "MaintfixeStartDate"), "yyyy-MM-dd")){
							preDate = gapAleVclDay.get(vclID);
						}else{
							preDate = MapGetter.getString(oneVcl, "MaintfixeStartDate");
						}
					}else{
						preDate = MapGetter.getString(oneVcl, "MaintfixeStartDate");
					}
				}else{
					continue;
				}
				int dayDef = DateRegUtil.getDaysOfTimeDef(new String[]{preDate,DateUtil.addDay(0)});
				String dayGap = MapGetter.getString(oneVcl,"MtnFS_MtnIn");
				int count = dayDef/(int)Float.parseFloat(dayGap);
				
				if(count>0){
					//保养计划提醒信息列表 录入
					this.maintAlertsDAO.InsertMaintList(oneVcl,dayGap,count,mtnType,isbakTable);
					String users = "";
					if(mtnAlertSMS){
						List<Map<String,Object>> userList = smsInfoDAO.getSMSUsersOfMtnNew("SMSAS_SMSMtn",MapGetter.getString(oneVcl, "DBCode"),MapGetter.getString(oneVcl, "VehicleID") );	
						users = this.smsInfoDAO.sendMailsOfmaintAlerts(userList,oneVcl,dayGap,mtnType,isbakTable);
					}
					oneVcl.put("armvalue", dayGap);
				}
			}
		}
		
	}
	/**
	 * 公里数
	 **/
	private void maintAlertsOfRunKm(float mtnInKm,
			List<Map<String, Object>> vclLists,boolean mtnAlertSMS,int mtnType,String isbakTable) {
		if(null!= vclLists && !vclLists.isEmpty()){
			for(Map<String,Object> oneVcl:vclLists){
				float tRunKm = Float.parseFloat(MapGetter.getString(oneVcl, "tRunKm"));
				int count = 0;
				String armvalue = "";
				if(tRunKm <= mtnInKm){//保内
					count = (int) tRunKm/(int)Float.parseFloat(MapGetter.getString(oneVcl,"MtnFS_MtnIn"));
					armvalue = String.valueOf(Float.parseFloat(MapGetter.getString(oneVcl,"MtnFS_MtnIn"))*count);
				}else{
					count = (int) tRunKm/(int)Float.parseFloat(MapGetter.getString(oneVcl,"MtnFS_MtnOut"));
					armvalue = String.valueOf(Float.parseFloat(MapGetter.getString(oneVcl,"MtnFS_MtnOut"))*count);
				}
				if(count>0){
					//未提示
					if(!this.maintAlertsDAO.checkMaintOfKmOrTime(mtnType,MapGetter.getString(oneVcl,"VehicleID"),armvalue,count)){
						//保养计划提醒信息列表 录入
						this.maintAlertsDAO.InsertMaintList(oneVcl,armvalue,count,mtnType,isbakTable);
						String users = "";
						if(mtnAlertSMS){
							List<Map<String,Object>> userList = smsInfoDAO.getSMSUsersOfMtnNew("SMSAS_SMSMtn",MapGetter.getString(oneVcl, "DBCode"),MapGetter.getString(oneVcl, "VehicleID"));
							users = this.smsInfoDAO.sendMailsOfmaintAlerts(userList,oneVcl,armvalue,mtnType,isbakTable);
						}
						oneVcl.put("armvalue", armvalue);
					}
				}
			}
		}
	}
	/**
	 * 保养方式为 工作小时数的 保养提示
	 **/
	private void maintAlertsOfWorkTime(float mtnInHours,
			List<Map<String, Object>> vclLists,boolean mtnAlertSMS,int mtnType,String isbakTable) {
		if(null!= vclLists && !vclLists.isEmpty()){
			for(Map<String,Object> oneVcl:vclLists){
				float tEWorkHours = Float.parseFloat(MapGetter.getString(oneVcl, "MsgSTP_tEWorkHours"));
				int count = 0;
				String armvalue = "";
				if(tEWorkHours<=mtnInHours){//保内
					count = (int)tEWorkHours/(int)Float.parseFloat(MapGetter.getString(oneVcl,"MtnFS_MtnIn"));
					armvalue = String.valueOf(Float.parseFloat(MapGetter.getString(oneVcl,"MtnFS_MtnIn"))*count);
				}else{
					count = (int)tEWorkHours/(int)Float.parseFloat(MapGetter.getString(oneVcl,"MtnFS_MtnOut"));
					armvalue = String.valueOf(Float.parseFloat(MapGetter.getString(oneVcl,"MtnFS_MtnOut"))*count);
				}
				if(count>0){
					if(!this.maintAlertsDAO.checkMaintOfKmOrTime(mtnType,MapGetter.getString(oneVcl,"VehicleID"),armvalue,count)){
						
						this.maintAlertsDAO.InsertMaintList(oneVcl,armvalue,count,mtnType,isbakTable);
						String users = "";
						if(mtnAlertSMS){
							List<Map<String,Object>> userList = smsInfoDAO.getSMSUsersOfMtnNew("SMSAS_SMSMtn",MapGetter.getString(oneVcl, "DBCode"),MapGetter.getString(oneVcl, "VehicleID"));
							users = this.smsInfoDAO.sendMailsOfmaintAlerts(userList,oneVcl,armvalue,mtnType,isbakTable);
						}
						oneVcl.put("armvalue", armvalue);
						//优化版本‘保养提示’要求关闭此处向提示表中插入数据  2015.1.12 SXH
						/*this.maintAlertsDAO.InsertPromtOfMaint(oneVcl,users,mtnType);*/
					}
				}
			}
		}
	}
	/**
	 * 此次保养提示处理的设备信息集
	 **/
	private Map<String, List<Map<String, Object>>> getWorkVclInfos() {
		List<Map<String,Object>> srcList = this.maintAlertsDAO.queryMaintAlertsVclsInfo();
		return new ListUtil().groupBy("MtnFS_MtnType", srcList);
	}
	/**
	 * 获取上次固定时间保养提示的信息
	 **/
	private Map<String, String> getPreMtnGapAlarmInfo() {
		Map<String,String> reMap = new HashMap<String,String>();
		List<Map<String,Object>> srcList = this.maintAlertsDAO.queryPreMtnGapAlarmInfo();
		if(null!=srcList&&!srcList.isEmpty()){
			reMap = new HashMap<String,String>();
			for(Map<String,Object> one:srcList){
				reMap.put(MapGetter.getString(one,"MtnAN_VclID"), MapGetter.getString(one,"MtnAN_AlarmDate"));
			}
		}
		return reMap;
	}
}
